# coding: utf-8
import os
import re
import sys
from pathlib import Path
from typing import Union

from PySide6.QtCore import QUrl, QFileInfo, QDir, QProcess
from PySide6.QtGui import QDesktopServices


def openUrl(url: Union[str, Path]):
    if isinstance(url, Path):
        url = url.as_posix()
    if not url.startswith("http"):
        if not os.path.exists(url):
            return False
        QDesktopServices.openUrl(QUrl.fromLocalFile(url))
    else:
        QDesktopServices.openUrl(QUrl(url))

    return True


def showInFolder(path: Union[str, Path]):
    """ 在文件浏览器中显示文件 """
    if not os.path.exists(path):
        return False

    if isinstance(path, Path):
        path = str(path.absolute())

    if not path or path.lower().startswith('http'):
        return False

    info = QFileInfo(path)  # type:QFileInfo
    if sys.platform == "win32":
        args = [QDir.toNativeSeparators(path)]
        if not info.isDir():
            args.insert(0, '/select,')

        QProcess.startDetached('explorer', args)
    elif sys.platform == "darwin":
        args = [
            "-e", 'tell application "Finder"', "-e", "activate",
            "-e", f'select POSIX file "{path}"', "-e", "end tell",
            "-e", "return"
        ]
        QProcess.execute("/usr/bin/osascript", args)
    else:
        url = QUrl.fromLocalFile(path if info.isDir() else info.path())
        QDesktopServices.openUrl(url)

    return True


def get_folder_size(folder: Union[Path, str]):
    if isinstance(folder, str):
        folder = Path(folder)
    size = 0
    for item in folder.glob('**/*'):
        if not item.is_file():
            continue
        size += item.stat().st_size
    return size


def ffmpeg_txt_sort(text: str):
    """ 对 ffmpeg 输出的文本进行排序 """

    def file_sort(x):
        return re.findall(r'\d+', x)[0]

    file_list = []
    for line in text.split('\n'):
        name = Path(line).name
        if 'file' in name:
            file_list.append(line)

    text = '\n'.join(sorted(file_list, key=file_sort))
    return text
